<template>
	<view>
		<view class="list-box">
			<view class="list">
				<view :ref="'jump'+index" :class="'jump'+index" v-for="(item, index) in list">
					<uni-section :sectionHeade="'sectionHeade'"
						:title="index + 1 + (item.tqType == '1' ?'.[单选题]  ':'.[判断题]  ') +item.title" type="line">
						<view class="uni-px-5 uni-pb-5">
							<kevy-radio :modeType="modeType" :items="item" :fontSize="28" color="#272727" :iconSize="30"
								iconColor="#329cfe" @radioClick="myClick($event, index)"></kevy-radio>
						</view>
						<view class="prompt"
							v-if="modeType == '1' && item.userAnswer && item.userAnswer !== item.bzAnswer">
							<text>你选择的答案 {{ item.userAnswer == null ? '未做' : item.userAnswer }}</text>
							<view>正确答案：<text class="stroke"> {{item.bzAnswer}}</text></view>
						</view>
						<view class="prompt" v-else>
							<text v-if="modeType == '2'">你选择的答案
								{{ item.userAnswer == null ? '未做' : item.userAnswer }}</text>
							<view>正确答案：<text class="stroke"> {{item.bzAnswer}}</text></view>
						</view>
					</uni-section>
				</view>
			</view>
		</view>
		<view class="btm-btn">
			<button v-if="modeType != '2'" class="btn" @click="submitPaper">交卷</button>
			<button class="btn" @click="AnswersListShow">答题卡</button>
		</view>
		<!-- 答题卡 -->
		<uni-popup ref="AnswersListPopup" background-color="#fff" type="top" @change="AnswersListChange">
			<view @click="closeAnswersList" class="iconfont icon-cuowu closeIcon"></view>
			<view class="popup-content">
				<text class="text">答题卡</text>
				<template v-if="modeType === '0'">
					<view class="ListBtns">
						<button @click="clickItem(item, 0)" class="btnMin"
							:class="{'btnGreen':!!item.userAnswer && item.userAnswer,}" size="mini"
							v-for="(item, index) in list">{{index+1}} </button>
					</view>
				</template>
				<template v-else>
					<view class="ListBtns">
						<button @click="clickItem(item, 0)" class="btnMin"
							:class="{'btnGreen':!!item.userAnswer && item.userAnswer == item.bzAnswer, 'btnRad': !!item.userAnswer && item.userAnswer !== item.bzAnswer}"
							size="mini" v-for="(item, index) in list">{{index+1}} </button>
					</view>
				</template>
			</view>
		</uni-popup>
		<!-- 交卷====有未做题目 -->
		<uni-popup ref="paperPopup" type="center">
			<view class="paper-box">
				<view @click="closePaperClose" class="iconfont icon-cuowu closeIcon"></view>
				<view class="submitPopupTxt">
					<text class="popup-title" style="color: #f00;">交卷提示</text>
					<view class="popup-sub">你还有<text style="color: #f00;">{{unSelectedNum.length}}</text>道题没做，确定交卷吗？
					</view>
				</view>
				<view class="paper-list">
					<button @click="clickItem(item, 1)" class="btnMin" size="mini"
						v-for="(item, index) in unSelectedNum">{{item.sortIndex+1}} </button>
				</view>
				<view class="submitPopupBtn">
					<button class="close-btn" @click="closePaperClose" type="default">取消</button>
					<button class="submit-btn" @click="confirmPaper" type="primary">确定交卷</button>
				</view>
			</view>
		</uni-popup>
		<!-- 考试成绩 -->
		<uni-popup ref="submitPopup" type="center">
			<view class="submit-popup-box">
				<view class="submitPopupTxt">
					<text class="popup-title">考试成绩</text>
					<view class="popup-sub">
						<text class="submit-name">{{ userInfo.username }}-{{ userInfo.IDcardNum }}</text>
						<text class="submit-type">{{ planName }}</text>
					</view>
					<view class="fraction">
						<text :style="{'color': passNum>85?'#f00':'#329cfe'}"
							class="fraction-num">{{ chooseCorrectly.length }}</text>分
					</view>
					<view class="prompt-box">
						<view style="background: #f00;color: #fff;" class="prompt-box-txt">
							<text>答错</text>
							<text>{{ selectionError.length }}</text>
						</view>
						<view style="background: #329cfe;color: #fff;" class="prompt-box-txt">
							<text>答对</text>
							<text>{{ chooseCorrectly.length }}</text>
						</view>
						<view v-if="unSelectedNum.length > 0" style="background-color: #b1b1b1;color: #fff;"
							class="prompt-box-txt">
							<text>未答</text>
							<text>{{ unSelectedNum.length }}</text>
						</view>
					</view>
					<view class="submit-list">
						<button @click="closeBlack" class="list-btn" type="default">关 闭</button>
					</view>
				</view>
			</view>
		</uni-popup>
	</view>
</template>

<script>
	// import atob from 'atob'
	import mock from '@/static/mockTM.json'
	import {
		getTestPaperDetail,
		getPaperList
	} from '@/api/index.js'
	import {
		decode64,
		formatDate,
		timeDifference
	} from '@/utils/index'
	export default {
		data() {
			return {
				startTime: '', // 开始做题时间
				endTime: '', // 交卷时间
				passNum: 85,
				radio1: 'A',
				countColor: '#000',
				list: [],
				items: [],
				text: '',
				modeType: '', // 0模拟考试 1 错题模式  2试卷模式
				haveQuestion: [], // 已经选择答题
				checkedIdx: '',
				clickIndex: '',
				unSelectedNum: [], // 未做题目
				selectedNum: [], // 已经做的题目
				chooseCorrectly: [], // 选择正确
				selectionError: [], // 选择错误
				userInfo: {},
				planId: "",
				examinationTime: '', //考试用时
				planName: '',
				id: '',
				errJson: [],
				userPlans:{}
			}
		},

		onLoad(val) {
			this.id = val.id
			this.modeType = val.type
			this.userInfo = uni.getStorageSync('userinfo')
			this.planId = uni.getStorageSync('planId')
			this.planName = uni.getStorageSync('planName')
			this.errJson = uni.getStorageSync('errJson').split(',')
			this.userPlans = this.userInfo.userPlans.find((item)=>{
				 if(item.opc == val.opc){
					return item
				}
			})
			this.loadData()
		},
		methods: {
			closeBlack() {
				this.$refs.submitPopup.close()
			},
			closePaperClose() {
				this.$refs.paperPopup.close()
			},
			myClick(val,index) {
				this.checkedIdx = val.index
				this.list[index].options[val.index].checked = !this.list[index].options[val.index].checked
				if (this.list[index].tqType == 2) {
					let item = val.item.options.map(e => {
						if (e.checked) {
							return e.value;
						}
					}).filter(value => value !== undefined);
					this.list[index].options[val.index].userAnswer = item.join()
					this.list[index].options[val.index].userAnswer = val.answer
				} else {
					this.list[index].options[val.index].userAnswer = val.answer
					this.list[index].userAnswer = val.answer
				}
			},
			loadData() {
				uni.showLoading({
					title: '题目生成中'
				})
				let params = {
					id: this.id,
					otype: this.otype,
					opcClassId:this.userPlans.opcClassId
				}
			
					getTestPaperDetail(params).then(res => {
						let data = []
						if (this.modeType === '1') {
							data = res.data.errQuestionList
						}
						if (this.modeType === '2') {
							data = res.data.userAnswerList
						}
						this.list = data.map((item, index, a) => {
							return {
								id: item.id,
								sort: item.sort,
								sortIndex: index,
								bzAnswer: item.answer,
								userAnswer: item.sAnswer,
								tqType: item.type,
								title: item.name,
								options: this.strSplit(item.options, item).map(p => ({
									...p,
									bzAnswer: item.answer
								}))
							}
						})
						// console.log(this.list);
						uni.hideLoading()
					})
			},
			getDifferenceSet(arr1, arr2, typeName) {
				return Object.values(arr1.concat(arr2).reduce((acc, cur) => {
					// console.log(acc, acc);
					if (acc[cur[typeName]] && acc[cur[typeName]][typeName] === cur[typeName]) {
						delete acc[cur[typeName]]
					} else {
						acc[cur[typeName]] = cur
					}
					return acc
				}, {}))
			},
			strSplit(val, item) {
				if (item.type == '3') {
					return [{
							text: `A、对`,
							value: '对'
						},
						{
							text: `B、错`,
							value: '错'
						}
					]
				} else {
					let tsStr = []
					
					tsStr = val.split('~!!~')
					
					const options = [];
					// 生成从 'A' 开始的字母数组，长度与 tsStr 一致
					const alphabet = Array.from({ length: tsStr.length }, (_, i) => String.fromCharCode(65 + i)); 
					tsStr.forEach((text, index) => {
						if(text) { // 确保文本不为空
							options.push({
								text: `${alphabet[index]}、${text}`,
								value: alphabet[index]
							});
						}
					});
					return options;
				}
			},
			Preprocessing(val, item) {
				if (item.score == '')
					return val
				let str = cheerio.load(decode64(val)).text()
				return str.replace(/\s*/g, "")
			},

			clickItem(item, val) {
				let index
				if (val === 1) {
					index = this.list.findIndex(e => e.sort === item.sort)
				} else {
					index = this.list.findIndex(e => e.id === item.id)
				}
				document.getElementsByClassName('jump' + index)[0].scrollIntoView({
					behavior: 'auto', //定义动画过渡效果"auto"或 "smooth" 之一。默认为 "auto"。
					block: 'center', //定义垂直方向的对齐， "start", "center", "end", 或 "nearest"之一。默认为 "start"。
					inline: 'start'
				})
				if (val === 1) {
					this.$refs.paperPopup.close()
				} else {
					this.$refs.AnswersListPopup.close()
				}
			},
			AnswersListShow() {
				this.$refs.AnswersListPopup.open()
			},
			AnswersListChange() {

			},
			closeAnswersList() {
				this.$refs.AnswersListPopup.close()
			},
			// 异位判断
			areStringsAnagrams(str1, str2) {
				if (str1 === undefined || str2 === undefined) {  
				    return false;  
				  }
			  // 如果字符串长度不同，直接返回false  
			   if (str1.length !== str2.length) {  
			     return false;  
			   }  
			   
			   // 创建一个对象来统计str1中每个字符的出现次数  
			   const charCount = {};  
			   for (let char of str1) {  
			     charCount[char] = (charCount[char] || 0) + 1;  
			   }  
			   
			   // 遍历str2，减去charCount中对应字符的计数  
			   for (let char of str2) {  
			     if (!charCount[char]) {  
			       // 如果str2中有str1中没有的字符，返回false  
			       return false;  
			     }  
			     charCount[char]--;  
			   }  
			   
			   // 检查charCount对象，确保所有字符的计数都为0  
			   for (let key in charCount) {  
			     if (charCount[key] !== 0) {  
			       return false;  
			     }  
			   }  
			   
			   // 如果所有检查都通过，返回true  
			   return true;  
			},
			// 交卷
			submitPaper() {
				this.unSelectedNum = [];
				this.selectedNum = []
				this.list.forEach((e, index, arr) => {
					if (!e.userAnswer) {
						this.unSelectedNum.push(e)
					} else {
						this.selectedNum.push(e)
					}
				})
				if (this.unSelectedNum.length >= 1) {
					this.$refs.paperPopup.open()
				} else {
					this.confirmPaper()
				}
			},
			// 确定交卷
			confirmPaper() {
				this.endTime = new Date()
				this.examinationTime = timeDifference(this.startTime, this.endTime)
				// console.log(formatDate(this.timeDifference,'hh:mm'));
				let chooseCorrectly = [] // 选择正确的题目
				let selectionError = [] // 选择错误的题目
				this.list.forEach((e, i, a) => {
					if (e.userAnswer !== '') {
						if (this.areStringsAnagrams(e.bzAnswer, e.userAnswer)) {
							chooseCorrectly.push(e)
						} else {
							selectionError.push(e)
						}
					}
				})
				this.chooseCorrectly = chooseCorrectly
				this.selectionError = selectionError
				let answerRecord = this.list.map(e => {
					return {
						'qid': e.id,
						userAnswer: e.userAnswer
					}
				})
				this.$refs.submitPopup.open()
				this.$refs.paperPopup.close()
			},
			markToRed(val, item) {
				let idex = item // 转化成以下形式
				let starStr = '<span style="color:#f00;text-decoration:underline;font-weight:bold;">' // 开头添加的字符串
				let endStr = '</span>' //尾添加的字符串
				let string = val
				let idxs = idex.split('-')
				let obj = {}
				// 根据标识是否加粗文字
				if (idex != '') {
					let obj = {}
					for (let i = 0; i < idxs.length; i++) {
						obj[idxs[i]] = `${starStr}${idxs[i]}${endStr}`
					}
					for (let [key, value] of Object.entries(obj)) {
						string = string.replace(new RegExp(key, "g"), value);
					}
					return string
				} else {
					return string
				}
			},
			optionToMarkToReds(item, val) {
				return item.map((i) => {
					return {
						bzAnswer: i.bzAnswer,
						text: this.markToRed(i.text, val),
						value: i.value
					}
				})
			},

		}
	}
</script>

<style lang="less" scoped>
	.list {
		.uni-pb-5 {
			padding-bottom: 0;
		}
	}

	.list-box {
		margin-top: 40rpx;
		padding-bottom: 100rpx;
	}

	.btm-btn {
		position: fixed;
		bottom: 0rpx;
		z-index: 2;
		width: 100%;
		display: flex;
		background-color: #f0f0f0;

		.btn {
			flex: 1;
		}
	}

	.countdown {
		position: fixed;
		top: 0;
		width: 100%;
		background-color: #f0f0f0;
		z-index: 2;

		.countdown-box {
			display: flex;
			text-align: center;
			align-items: center;
			justify-content: center;
			background-color: #f0f0f0;
			padding: 8rpx;
		}

		.zw {
			// height: var(--status-bar-height);
			height: 90rpx;
			width: 100%;
		}
	}

	.closeIcon {
		position: absolute;
		right: 36rpx;
		top: 6rpx;
		font-size: 38rpx;
		z-index: 9;
	}

	.popup-content {
		text-align: center;

		.text {
			display: block;
			padding: 8rpx 0;
		}
	}

	.ListBtns {
		display: flex;
		flex-wrap: wrap;

		.btnMin {
			padding: 0 20rpx;
			margin: 3rpx 8rpx;
			min-width: 90rpx;
		}

		.btnRad {
			background-color: #f00;
			color: #fff;
		}

		.btnGreen {
			background-color: green;
			color: #fff;
		}
	}

	.submitPopupTxt {
		text-align: center;
		padding-bottom: 30rpx;
		padding-top: 10rpx;

		.popup-title {
			display: block;
			padding: 10rpx 0;
			font-size: 40rpx;
		}

		.popup-sub {
			display: block;
			padding: 0 20rpx;
			font-size: 35rpx;
		}
	}

	.paper-box {
		background-color: #fff;
		border-radius: 20rpx;
		min-width: 600rpx;
		min-height: 500rpx;
		display: flex;
		flex-direction: column;
		justify-content: space-between;

		.paper-list {
			// margin: 0 10rpx;
			padding: 0 10rpx;
			margin-bottom: 30rpx;
		}

		.btnMin {
			padding: 0 !important;
			width: 10%;
		}


		.submitPopupBtn {
			display: flex;

			.close-btn {
				flex: 1;
			}

			.submit-btn {
				flex: 1;
			}
		}
	}

	.submit-popup-box {
		background-color: #fff;
		border-radius: 20rpx;
		margin: 0 20rpx;
		width: 600rpx;

		.submitPopupTxt {}

		.popup-sub {
			padding: 5px 15rpx;
			font-size: 13px;
			border-bottom: 1px dashed #333;
		}

		.submit-name {
			display: block;
		}

		.fraction {
			display: flex;
			justify-content: center;
			align-items: baseline;
			border-bottom: 1px solid #a29f9f;

			.fraction-num {
				font-weight: bold;
				font-size: 68rpx;
			}
		}

		.timePaper {
			display: block;
			font-size: 12px;
			// padding: 5rpx 0;
			border-bottom: 1px solid #a29f9f;
		}

		.submit-list {
			display: flex;

			.list-btn {
				flex: 1;
			}
		}

		.prompt-box {
			display: flex;
			justify-content: space-around;
			border-bottom: 1px solid #a29f9f;
			margin-bottom: 30rpx;

			.prompt-box-txt {
				padding: 10rpx 0;
				border-left: 1px solid #a29f9f;
				display: flex;
				flex-direction: column;
				justify-content: center;
				align-items: center;
				flex: 1;
			}
		}
	}

	.prompt {
		display: flex;
		flex-direction: column;
		background-color: #8b8d8f;
		color: #fff;
		padding: 10rpx 20rpx;
		// margin: 0 15rpx;
	}

	.analysis {
		font-size: 28rpx;
		background: #ff00006e;
		color: #333;
		padding-top: 15rpx;
	}

	.stroke {
		color: rgb(255, 0, 0);
		-webkit-text-stroke: 1rpx white;
		font-weight: 700;
	}
</style>